using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using SecurityInfoTest;
using System.Security.AccessControl;
using GCAWeb.Utils;
using System.Security.Principal;

namespace DirectorySecurity
{
    public partial class Form1 : Form
    {


        public Form1()
        {
            InitializeComponent();
        }

        private void btOpen_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                tbPath.Text = folderBrowserDialog1.SelectedPath;
        }

        private void btScan_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(tbPath.Text))
            {
                UserFileAccessRights rights = new UserFileAccessRights(tbPath.Text);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(tbPath.Text))
            {
                DirectoryInfo di = new DirectoryInfo(tbPath.Text);
                foreach (DirectoryInfo d in di.GetDirectories())
                {
                    System.IO.FileInfo fi = new System.IO.FileInfo(d.FullName);
                    GetFileRights(fi);
                }
            }

            dataGridView1.AutoResizeColumns();

            
        }

        private void GetFileRights(System.IO.FileInfo fi)
        {
            try
            {

                AuthorizationRuleCollection acl = fi.GetAccessControl().GetAccessRules
                    (true, true, typeof(NTAccount));
                            //(true, true, typeof(SecurityIdentifier));
                bool first = true;
                foreach (AuthorizationRule rule in acl)
                //for (int i = 0; i < acl.Count; i++)
                {
                    System.Security.AccessControl.FileSystemAccessRule r = rule as System.Security.AccessControl.FileSystemAccessRule;
                    //WindowsIdentity _principal = new WindowsIdentity(rule.IdentityReference.Value);
                    dataSet.tRights.AddtRightsRow(
                        first ? fi.FullName : "",
                        rule.IdentityReference.Value,
                        rule.IsInherited.ToString(),
                        r.FileSystemRights.ToString());

                    first = false;
                }
            }
            catch (Exception ex)
            {

                //throw;
            }
        }


    }
}